package com.lhl.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class MongoHelper {

    private String dbName;
    private String serverAddress;
    private int port;

    private MongoClient mongoClient = null;
    private MongoDatabase mongoDataBase = null;

    public MongoHelper(String serverAddress, int port, String dbName) {
        this.dbName = dbName;
        this.serverAddress = serverAddress;
        this.port = port;
    }

    /**
     *
     * @param collection 表名
     * @return
     */
    public MongoDao getDao(String collection){
        return new MongoDao(getMongoDataBase(),collection);
    }

    /**
     * 关闭数据库和连接
     */
    public void disconnect() {
        if (mongoDataBase != null) {
            mongoDataBase = null;
        }
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

    /**
     * 连接mongodb
     * @return
     */
    private MongoClient getMongoClient(){
        try {
            // 连接到 mongodb 服务
            if(mongoClient==null){
                mongoClient = new MongoClient(serverAddress, port);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mongoClient;
    }

    /**
     * 打开数据库
     * @return
     */
    private MongoDatabase getMongoDataBase() {
        try {
            // 连接到数据库
            mongoDataBase = getMongoClient().getDatabase(dbName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mongoDataBase;
    }

}